package com.red.wine.ui;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.red.wine.R;
import com.red.wine.WineApp;
import com.red.wine.model.Headers;
import com.red.wine.model.LoginReturn;
import com.red.wine.model.NodeReq;
import com.red.wine.model.PerfectData;
import com.red.wine.model.PerfectReq;
import com.red.wine.model.RegisterReturn;
import com.red.wine.model.SignData;
import com.red.wine.model.SignReq;
import com.red.wine.util.BitmapUtil;
import com.red.wine.util.IntentUtil;
import com.red.wine.util.PersistentKeyUtil;
import com.red.wine.util.PrefsUtils;
import com.red.wine.util.StringUtil;
import com.red.wine.webservice.ServiceAsynTask;
import com.red.wine.webservice.ServiceHelper;
import com.red.wine.webservice.ServiceHost;

import android.app.AlertDialog.Builder;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class PerInfoActivity extends BaseActivity{
	private ImageView back;
	private Context context;
	private ImageView changiconImg;
	private TextView nicheng,xingbie,city;
	/**选择性别*/
    private String[] setString = {"男","女"};
    private Dialog dialog;
    private Builder builder;
    private Spinner spinner;
    private EditText putnicheng;
    int spinner_index = -1;
    private int index =0;
    private TextView textView;
    private Button saveBtn;
    String getnicheng;
    private int index_sp = -1;
    private String name;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.perfect_info);
		context = this;
		builder = new AlertDialog.Builder(context);
		View view = LayoutInflater.from(context).inflate(R.layout.sex_choice, null);
		saveBtn = (Button) findViewById(R.id.per_save_btn);
		spinner = (Spinner) view.findViewById(R.id.sex_choice);
		putnicheng = (EditText) view.findViewById(R.id.nicheng_edit);
		textView = (TextView) view.findViewById(R.id.sex_choice_title);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
		for(String s:setString){
			adapter.add(s);
		}
		adapter.setDropDownViewResource(R.layout.account_type_drop_down_item);
		spinner.setAdapter(adapter);
		builder.setView(view);
		
		spinner.setSelection(spinner_index);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				spinner_index = arg2;
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				if(index == 1){
				 xingbie.setText(setString[spinner_index]);
				 index_sp = spinner_index;
				}else if(index == 2){
					getnicheng = putnicheng.getText().toString().trim();
					if(!StringUtil.isEmptyOrNull(getnicheng)){
						name = getnicheng;
						nicheng.setText(getnicheng);
					}else{
						Toast.makeText(context, "昵称不能为空", Toast.LENGTH_SHORT).show();
						return;
					}
				}
				 dialog.dismiss();
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		dialog = builder.create();
		back = (ImageView) findViewById(R.id.top_back_btn_5);
		changiconImg = (ImageView) findViewById(R.id.change_persion_icon_img);
		nicheng = (TextView) findViewById(R.id.nicheng);
		xingbie = (TextView) findViewById(R.id.xingbie);
		city = (TextView) findViewById(R.id.city);
		if(StringUtil.isEmptyOrNull(PrefsUtils.getDyName())){
			nicheng.setText("未设置");
		}else{
			nicheng.setText(PrefsUtils.getDyName());
		}
		if(StringUtil.isEmptyOrNull(PrefsUtils.getCity())){
			city.setText("未设置");
		}else{
			city.setText(PrefsUtils.getCity());
		}
		if(!StringUtil.isEmptyOrNull(PrefsUtils.getSex())){
			xingbie.setText(PrefsUtils.getSex());
		}else{
			xingbie.setText("未设置");
		}
		city.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				PrefsUtils.setFrom("2");
				IntentUtil.redirectToNext(context, CityActivity.class, bundle);
//				finish();
			}
		});
		nicheng.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				textView.setText("昵称设置");
				index = 2;
				putnicheng.setVisibility(View.VISIBLE);
				spinner.setVisibility(View.GONE);
				dialog.show();
			}
		});
		xingbie.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				textView.setText("性别设置");
				index = 1;
				putnicheng.setVisibility(View.GONE);
				spinner.setVisibility(View.VISIBLE);
				dialog.show();
			}
		});
		back.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				IntentUtil.redirectToNext(context, MyCenterActivity.class);
				finish();
			}
		});
		initPopu();
		 
		changiconImg.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
//				popuWindow.showAtLocation(v,Gravity.RIGHT, 20, 40);	
				popuWindow.showAsDropDown(v);
			}
		});
		
		from_camera.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				popuWindow.dismiss();
				String status = Environment.getExternalStorageState();
				if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
					doTakePhoto();// 用户点击了从照相机获取
				} else {
					Toast.makeText(context, "没有SD卡",Toast.LENGTH_SHORT).show();
				}	
				haseImage = true;
			}
		});
		fron_loc.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				popuWindow.dismiss();
				Intent intent3 = new Intent(Intent.ACTION_GET_CONTENT);  
	            intent3.addCategory(Intent.CATEGORY_OPENABLE);  
	            intent3.setType("image/*");  
	            intent3.putExtra("crop", "true");  
	            intent3.putExtra("aspectX", 1);  
	            intent3.putExtra("aspectY", 1);  
	            intent3.putExtra("outputX", 64);  
	            intent3.putExtra("outputY", 64);  
	            intent3.putExtra("return-data", true);  
	            startActivityForResult(intent3, 3);  
			}
		});
		
		saveBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				if(WineApp.getInstance().isNetworkAvailable() || WineApp.getInstance().isWiFiActive()){
//					sendImg();
					if(StringUtil.isEmptyOrNull(getnicheng)&&(spinner_index == -1)&&StringUtil.isEmptyOrNull(city_id)){
						Toast.makeText(context, "名称、性别、所在城市不能全部为空", Toast.LENGTH_SHORT).show();
					}else{
						sendInfo(name,index_sp, !StringUtil.isEmptyOrNull(city_id)?city_id:"");
					}
				}else{
					Toast.makeText(context, "无可用网络", Toast.LENGTH_SHORT).show();
				}
					
			}
		});
	}
	
	private String city_id = "";
	private void sendImg() {
//		new Thread() {
//			public void run() {
				if(iconBitmap != null){
					 String end ="\r\n";
				        String twoHyphens ="--";
				        String boundary ="*****";
				        try
				        {
				          URL url =new URL(ServiceHost.getTasteURL());
				          HttpURLConnection con=(HttpURLConnection)url.openConnection();
				          /* 允许Input、Output，不使用Cache */
				          con.setDoInput(true);
				          con.setDoOutput(true);
				          con.setUseCaches(false);
				          /* 设置传送的method=POST */
				          con.setRequestMethod("POST");
				          /* setRequestProperty */
				          con.setRequestProperty("Connection", "Keep-Alive");
				          con.setRequestProperty("Charset", "UTF-8");
				          con.setRequestProperty("Content-Type",
				                             "multipart/form-data;boundary="+boundary);
				          /* 设置DataOutputStream */
				          DataOutputStream ds =  new DataOutputStream(con.getOutputStream());
				          ds.writeBytes(twoHyphens + boundary + end);
				          ds.writeBytes("Content-Disposition: form-data; "+
				                        "name=\"photo\";filename=\""+
				                        BitmapUtil.bitmapToBytes(iconBitmap)+"\"" + "\r\n\r\n");
				          
				          NodeReq req = new NodeReq();
				          req.cmd = "user_setavatar";
				          req.sid = "7b8bb3e017b56d612123e564f5594d3006217f";
				          
				          Headers headers = new Headers();
				          headers.setLang("zh-chs");
				          headers.setUa("ANDROID/1.5.0.0");
				          
				          String renody =new Gson().toJson(req);
				          String reqBody = new Gson().toJson(renody);
				          reqBody = reqBody + "\r\n\r\n";
				          ds.write(reqBody.getBytes("ISO-8859-1"));
						/* 取得Response内容 */
						InputStream is = con.getInputStream();
						int ch;
						StringBuffer b = new StringBuffer();
						while ((ch = is.read()) != -1) {
							b.append((char) ch);
						}
						/* 将Response显示于Dialog */
						Log.e("上传成功", b.toString().trim());
						/* 关闭DataOutputStream */
						ds.close();
					} catch (Exception e) {
						e.printStackTrace();
						Log.e("上传失败", "========");
					}
				} 
//			}
//		}.start();
	};
	
	private void sendInfo(final String name, final int gender, final String city){
		showLoading();
		new ServiceAsynTask<RegisterReturn>() {

			@Override
			protected RegisterReturn callService() throws IOException,
					JsonParseException, AssertionError {
				PerfectReq taste= new PerfectReq();
				Headers header = new Headers();
				header.setUa("ANDROID_HY/2.0.1.0 (customerid=gypsii, variant=gypsii)");

				PerfectData data = new PerfectData();
				Log.e("TAG", "昵称: = " + name + " , gender: =" + gender);
				if(!StringUtil.isEmptyOrNull(name)){
					data.setName(name);
				}else{
					data.setName("");
				}

				if (gender == -1) {
					data.setGender("");
				} else if (gender == 0) {
					data.setGender("M");
				} else if (gender == 1) {
					data.setGender("F");
				}
					
				if(!StringUtil.isEmptyOrNull(city)){
					data.setCity(city);
				}else{
					data.setCity("");
				}

				taste.cmd = "user_setinfo";
				taste.headers = header;
				taste.data = data;
				taste.sid = "7b8bb3e016fb16f49bc4dd26b7b484ae9bedc3";

				String up = new Gson().toJson(taste);
				String send = StringUtil.unicodeToUtf8("json=" + up);
				String urlstr = ServiceHost.getTasteURL();

				return ServiceHelper.getInstance().postData(urlstr, send,
						RegisterReturn.class);
			}

			@Override
			protected void runWithResult(RegisterReturn result) throws Exception {
				
				if (result != null && result.getRsp().equals("1")) {
					Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
					
					Log.e("TAG", "isnotnull");
					PrefsUtils.setDyName(getnicheng);
					if(gender != -1){
						if(gender == 0){
							PrefsUtils.setSex("男");
						}else if(gender == 1){
							PrefsUtils.setSex("女");
						}
					}else{
						PrefsUtils.setSex(null);
					}
					PrefsUtils.setCity(!StringUtil.isEmptyOrNull(cityname)?cityname:null);
					IntentUtil.redirectToNext(context, MyCenterActivity.class);
					finish();
				} else {
					Log.e("TAG", "is null");
					Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
				}
				
				hideLoading();
			}

			@Override
			protected void runWithError(RegisterReturn result, int iErrorCode)
					throws Exception {
				Log.e("TAG", "异常");
				hideLoading();
			}
		}.execute();
	}
	
	private String cityname = "";
	@Override
	protected void onResume() {
		if(!StringUtil.isEmptyOrNull(PrefsUtils.getFrom())){
			if(PrefsUtils.getFrom().equals("2")){
				PrefsUtils.setFrom(null);
			}
		}
		if(!StringUtil.isEmptyOrNull(PrefsUtils.getCityName())){
			String[] citys = PrefsUtils.getCityName().split(":");
			if(city !=null){
				city.setText(!StringUtil.isEmptyOrNull(PrefsUtils.getCityName()) ? citys[0] :"");
			}
			city_id = citys[1];
			PrefsUtils.setCityName(null);
		}
		Log.e("TAG", "city_id: = " + city_id);
		super.onResume();
	}
	private static final int CAMERA_WITH_DATA = 3023;
	/* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	/* 拍照的照片存储位置 */
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/red/CameraCache");
	private static File mCurrentPhotoFile;// 照相机拍照得到的图片
	Uri imgUri;
	private PopupWindow popuWindow;
	private View popuView;
	private Button fron_loc;
	private Button from_camera;
	private boolean haseImage = false;
	private void initPopu(){
		popuView = LayoutInflater.from(context).inflate(R.layout.choice_persion_popu, null);
		from_camera = (Button) popuView.findViewById(R.id.get_from_camera);
		fron_loc = (Button) popuView.findViewById(R.id.get_from_loc);
		popuWindow = new PopupWindow(popuView,
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		popuView.setFocusableInTouchMode(true);
		popuWindow.setFocusable(true);
		ColorDrawable dw = new ColorDrawable(Color.HSVToColor(0x11,
				new float[] { 00, 00, 0xff }));
		popuWindow.setBackgroundDrawable(dw);
		popuWindow.setOutsideTouchable(true);
	}
	
	/**
	 * 拍照获取图片
	 */
	protected void doTakePhoto() {
		try {
			// Launch camera to take photo for selected contact
			if (!PHOTO_DIR.exists()) {
				PHOTO_DIR.mkdirs();
			}
			String FileName = System.currentTimeMillis() + ".jpg";
			mCurrentPhotoFile = new File(PHOTO_DIR, FileName);
			PrefsUtils.setImageFile(mCurrentPhotoFile.getAbsolutePath());
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
			Toast.makeText(this, "photoPickerNotFoundText", Toast.LENGTH_LONG)
					.show();
		}
	}
	
	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}
	
	protected void doCropPhoto(File f) {
		try {
			// 启动gallery去剪辑这个照片
			final Intent intent = getCropImageIntent(Uri.fromFile(f));
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "失败", Toast.LENGTH_LONG).show();
		}
	}
	
	/**
	 * Constructs an intent for image cropping. 调用图片剪辑程序 剪裁后的图片跳转到新的界面
	 */
	public static Intent getCropImageIntent(Uri photoUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 64);
		intent.putExtra("outputY", 64);
		intent.putExtra("return-data", true);
		return intent;
	}
	private Bitmap iconBitmap = null;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK)
			return;
		switch (requestCode) {
		case PHOTO_PICKED_WITH_DATA:
			Bundle extras = data.getExtras();

			if (extras != null) {
				iconBitmap = extras.getParcelable("data");
				if (iconBitmap == null) {
					Toast.makeText(this, "头像设置失败", Toast.LENGTH_SHORT).show();
				}

				if (changiconImg != null) {
					changiconImg.setImageBitmap(iconBitmap);
					saveCamera(iconBitmap, false);
				}
				if (haseImage) {
					 Toast.makeText(context, "拍照成功", Toast.LENGTH_SHORT).show();
				}
			}
			break;
		case CAMERA_WITH_DATA:
			if (mCurrentPhotoFile != null){
				doCropPhoto(mCurrentPhotoFile);
			}else{
				File ff= new File(PrefsUtils.getImageFile());
				doCropPhoto(ff);
			}
			break;
		case 3:   
             iconBitmap = (Bitmap) data.getExtras().get("data");   
            try {   
            	if(iconBitmap != null){
            		if (changiconImg != null)
    					changiconImg.setImageBitmap(iconBitmap);
            		saveCamera(iconBitmap, false);
            	}
            } catch (Exception e) {   
                e.printStackTrace();   
            }   
               
            break;   
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	 
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			IntentUtil.redirectToNext(context, MyCenterActivity.class);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void saveCamera(Bitmap theBmp, boolean recycle) {
		byte[] data = null;
		try {
			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			theBmp.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
			data = bytes.toByteArray();
			bytes.close();
			if (recycle)
				theBmp.recycle();
		} catch (Exception e) {
			// Log.e("imag", "保存图片异常");
			if (theBmp != null) {
				theBmp.recycle();
			}
			e.printStackTrace();
		}
		theBmp = null;
		// make URI to save image
		SimpleDateFormat timeStampFormat = new SimpleDateFormat(
				"yyyyMMddhh.mm.ss");
		String filename = timeStampFormat.format(new Date());
		filename = filename + ".jpg";
		ContentValues values = new ContentValues();
		values.put(Media.TITLE, filename);
		values.put(Media.DISPLAY_NAME, filename);
		values.put(Media.DESCRIPTION, "Image capture by camera");
		values.put(Media.MIME_TYPE, "image/jpeg");

		String directory = WineApp.getInstance().getFilePath();
		String filepath = directory + "/" + filename;
		values.put("_data", filepath);

		// Log.e("iamgeURL", "befor imageUri");
		imgUri = getContentResolver()
				.insert(Media.EXTERNAL_CONTENT_URI, values);
		// Log.e("iamgeURL", "after imageUri");

		try {
			OutputStream filoutputStream = getContentResolver()
					.openOutputStream(imgUri);
			filoutputStream.write(data);
			filoutputStream.flush();
			filoutputStream.close();

		} catch (Exception ex) {
			// Log.e("iamgeURL", "imagURL is error");
			imgUri = null;
			Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
		}
		data = null;
		System.gc();

		PrefsUtils.setReportImagePath(filepath);
	}
}
